﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using UFSoft.UBF.Util.Log;

namespace UFIDA.U9.Cust.XH.PlugBE.Tool
{
    public static class OARestful
    {

        public static string CallAPI(string action, string postDataStr, string billtype)
        {
            string url = OAUrlHelper.OAUrl + action;
            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
            Encoding encoding = Encoding.GetEncoding("utf-8");  //字符编码   
            string currentDateTime = DateTime.Now.ToString("yyyyMMddHHmmss");
            string sysid = OAUrlHelper.Systemid;
            string psw = OAUrlHelper.D_Password;
            string md5 = GetMd5Hash(sysid + psw + currentDateTime).ToLower();
            request.Headers.Add("systemid", sysid);
            request.Headers.Add("currentDateTime", currentDateTime);
            request.Headers.Add("Md5", md5);

            request.Method = "Post";   //请求方式            
            request.ContentType = "application/x-www-form-urlencoded;charset:utf-8";
            //超时时间为5分钟
            request.Timeout = 5 * 60 * 1000;
            StringBuilder paraStrBuilder = new StringBuilder();
            paraStrBuilder.AppendFormat("{0}={1}&", "datajson", postDataStr);
            string para = paraStrBuilder.ToString();
            byte[] bt = Encoding.UTF8.GetBytes(para);
            string responseData = String.Empty;
            request.ContentLength = bt.Length;
            //GetRequestStream 输入流数据
            using (Stream reqStream = request.GetRequestStream())
            {
                reqStream.Write(bt, 0, bt.Length);
                reqStream.Close();
            }
            try
            {
                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {
                    Stream stream = response.GetResponseStream();
                    using (StreamReader streamReader = new StreamReader(stream, Encoding.UTF8))
                    {
                        string content = streamReader.ReadToEnd().ToString();
                        Log(string.Format("类型：{0}; 返回报文：{1} ", billtype, content));
                        return content;
                    }
                }
            }
            catch (Exception ex)
            {
                string errorMsg = string.Format("与OA通讯异常：{0}；提交的地址：{1}", ex.Message, url);
                Log(string.Format("类型：{0};{1} ", billtype, errorMsg));
                throw new Exception(errorMsg);
            }
        }

        private static ILogger logger = LoggerManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
        /// <summary>
        /// 写字符串日志
        /// </summary>
        /// <param name="msg">日志明细</param>
        public static void Log(string msg)
        {
            //ILogger logger = LoggerManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

            //logger.IsInfoEnabled;

            //if (logger.IsErrorEnabled)
            {
                logger.Error(msg);
            }
        }

        public static string GetMd5Hash(string str)
        {
            using (MD5 md5Obj = MD5.Create())
            {
                var md5Bytes = md5Obj.ComputeHash(Encoding.UTF8.GetBytes(str));
                //md5Obj.Dispose();
                StringBuilder builder = new StringBuilder();
                for (int i = 0; i < md5Bytes.Length; i++)
                {


                    builder.Append(md5Bytes[i].ToString("X2"));//3500元
                }
                return builder.ToString();
            }
        }


    }
}
